<template>
  <div class="fill-width-height flex-col" style="overflow: auto;padding: 10px;">
    <el-row :gutter="10" class="mb8" v-if="isEdit">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="!single" @click="handleUpdate">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="!single" @click="handleDetail">添加图库内的图片</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="!single" @click="addExtLink">添加外部图片路径</el-button></el-col>
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-edit" size="mini" @click="getPageData">刷新</el-button></el-col>
    </el-row>

    <div class="fill-width">
      <TypeMenu :typeList="typeList" v-model="activeId" @itemClick="clickType"/>
    </div>

    <el-row :gutter="24" class="flex-1 overflow-auto">
      <el-col :md="6" :lg="4" :xl="3" :xs="12" :sm="12" v-for="(row, index) in tableData" :key="index" style="padding-top:8px;padding-bottom: 8px;">
        <el-card
          :body-style="{ padding: '10px' }"
          shadow="hover"
          style="cursor: pointer;"
          @click.native.prevent="() => row.selected = !row.selected"
        >
          <template #header>
            <div class="flex-row justify-between items-center justify-center">
              <el-checkbox v-model="row.selected"></el-checkbox>
              <span></span>
              <el-button type="text" round size="mini" @click.stop="expandChange(row)">合集</el-button>
              <el-switch
                v-model="row.status"
                active-value="0"
                inactive-value="1"
                @change="toggleStatus(row)"
              ></el-switch>
            </div>
          </template>

          <LazyLoadImage
            class="fill-width"
            fit="contain"
            :src="getImg(row)"
            :lazy="true"
            style="width: fit-content; height: 100px;"
          >
          </LazyLoadImage>

          <div class="text-container text-center">
            <p class="text-overflow-hidden">{{ row.collname }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="fill-width">
      <el-divider></el-divider>
      <el-pagination
        style="padding-top: 10px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[30, 20, 100, 200]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <ItemForm :item="itemObj" :mode="mode" ref="itemFormRef" @callBack="() => getDetailsList(itemObj.id,itemObj)"/>
    <ItemDetail ref="itemDetailRef" :collId="collId"/>

    <!-- 添加外部图片链接对话框 -->
    <el-dialog
      :visible.sync="linkDialogVisible"
      title="添加外部图片链接"
      @close="handleDialogClose"
      :z-index="888"
    >
      <div style="padding: 10px;">
        <el-button type="primary" @click="addLink">添加链接</el-button>
        <el-button type="primary" @click="addCrawlerLinkImg">选择爬取的图片</el-button>
      </div>
      <el-table :data="linkList" style="width: 100%">
        <el-table-column label="图片链接">
          <template #default="scope">
            <div class="flex-row justify-center align-center" style="gap: 10px;" >
              <img v-if="scope.row.link.length > 0" :src="scope.row.link"  alt="" style="width: 80px;"/>
              <el-input v-model="scope.row.link" placeholder="请输入图片链接"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="mini" @click="deleteLink(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="linkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveLinks">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="selectImgDialogVisible" width="90%" title="选择爬取任务的图片" :z-index="999" modal-append-to-body>
      <div class="fill-width-height dialog-content flex-col">
        <ImageCrawlerSelectData ref="imageCrawlerRef" class="flex-1" style="min-height: 0;overflow: hidden"/>
        <el-divider style="margin: 0"/>
        <div class="d-flex align-center justify-center">
          <el-button type="primary" @click="configSelect">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <el-drawer
      :visible.sync="drawerVisible"
      title="合集内容"
      size="50%"
    >
      <div class="fill-width" v-if="isEdit">
        <div class="flex-row align-center" style="gap: 10px;padding: 0 12px;" >
          <span>全选：&nbsp;&nbsp;</span>
          <el-checkbox v-model="allSelected" @change="allSelectedChange(currentRow.detailList)"></el-checkbox>
          <el-button type="danger" size="mini" icon="el-icon-delete" class="button" @click.stop="deleteItem(currentRow)">删除</el-button>
          <div ></div>
        </div>
        <div style="height: 10px;"></div>
        <el-divider/>
      </div>

      <el-row :gutter="24" :justify="'left'" :key="currentRow.id" style="margin: 0;margin-top: 10px;">
        <el-col :md="8" :lg="8" :xl="8" :xs="12" :sm="12" v-for="(item, index) in  currentRow.detailList || []" :key="index">
          <el-card :body-style="{ padding: '0px' }" shadow="hover" style="cursor: pointer;" class="flex-col justify-center align-center" >
            <div slot="header" class="clearfix" v-if="isEdit">
              <el-checkbox v-model="item.selected"></el-checkbox>
            </div>
            <LazyLoadImage
              class="fill-width"
              fit="contain"
              :src="getPreviewPath(item.imginfoid,item)"
              :lazy="true"
              style="width: fit-content; height: 150px;"
              @click.stop="clickItems(item,currentRow.detailList)"
            >
            </LazyLoadImage>
          </el-card>
        </el-col>
      </el-row>
    </el-drawer>

  </div>
</template>

<script>
import { deleteByIds, getImgCollectPage } from '@/api/imgManage/imgCollect'
import { deleteImgCollectDetailByIds, getImgCollectDetailList } from '@/api/imgManage/imgCollectDetail'
import { directionOptions } from '@/views/imgManage/homeManage/homeHook'
import { getToken } from '@/utils/auth'
import {getList} from "@/api/imgManage/imgType";
import {listToTree} from "@/utils";
import TypeMenu from '../typeMenu'
import { update } from "@/api/imgManage/imgCollect";
import { saveList } from '@/api/imgManage/imgCollectDetail'
import ImageCrawlerSelectData from '@/views/imgManage/imageCrawler/selectData'
import LazyLoadImage from '@/components/LazyLoadImage/index.vue'
export default {
  name: 'collectionManage',
  components: {
    LazyLoadImage,
    ItemForm: () => import('./itemForm'),
    ItemDetail: () => import('./itemDetail'),
    TypeMenu,
    ImageCrawlerSelectData
  },
  props: {
    isEdit: {
      type: Boolean,
      default: () => true
    }
  },
  data(){
    return {
      selectImgDialogVisible: false,
      linkDialogVisible: false,
      linkList: [],

      activeId: 'all',
      allObj: { value:'all', label: '全部' ,id:'all', name: '全部', level: 1 },
      typeList: [],

      allSelected: false,
      selectDetailList: [],
      detailList: [],
      tableData: [],
      // multipleSelection: [],
      // single: true,
      // multiple: false,
      mode: 'add',
      itemObj: {
        id: '',
        title: '',
        cardtype: '',
        ordernum: 0
      },
      uploadFileUrl: '',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 30,
      },
      drawerVisible: false,
      currentRow: {}
    }
  },
  computed: {
    collId(){
      return this.multipleSelection?.length > 0 ? this.multipleSelection[0].id : ''
    },
    multipleSelection(){
      return this.tableData.filter(item => item.selected)
    },
    single(){
      return this.multipleSelection.length === 1
    },
    multiple(){
      return this.multipleSelection.length > 1
    }
  },
  methods: {
    addCrawlerLinkImg(){
      this.selectImgDialogVisible = true
      this.$refs.imageCrawlerRef?.initSelectData()
    },
    configSelect(){
      const data = this.$refs.imageCrawlerRef?.getSelectedData() || []
      data?.forEach(item => {
        this.linkList.push({ link: item.imageSrc })
      })
      this.selectImgDialogVisible = false
    },
    handleDialogClose(){
      this.linkDialogVisible = false
    },
    addExtLink(){
      this.linkList = []
      this.linkDialogVisible = true
    },
    addLink() {
      this.linkList.push({ link: '' })
    },
    deleteLink(index) {
      this.linkList.splice(index, 1)
    },
    saveLinks() {
      if(this.linkList.length <= 0){
        return this.$modal.msgWarning("请添加数据！")
      }
      console.log('保存的链接列表:', this.linkList.map(item => item.link))
      const linkList = this.linkList.filter(item => item?.link?.length > 0 )
      const submitList = linkList.map((item,index) => {
        const resMap = {
          collid: this.collId,
          imginfoid: item.link,
          ordernum: index + 1
        }
        return resMap
      })
      saveList(submitList).then(res => {
        this.linkDialogVisible = false
        this.getPageData()
      })
    },
    // ----------- 添加外部图片结束-------------------

    allSelectedChange(detailList){
      setTimeout(() => {
        detailList.forEach(item => {
          this.$set(item,'selected', this.allSelected)
        })
        this.selectDetailList = this.selectDetailList = detailList
          .filter(item => item.selected)
          .map(item => item.id)
      },50)
    },
    clickItems(item,detailList){
      this.$set(item,'selected',!item.selected)
      this.selectDetailList = detailList
        .filter(item => item.selected)
        .map(item => item.id)
    },
    deleteItem(item){
      if(this.selectDetailList?.length <= 0){
        this.$modal.msgWarning("请选择要删除的数据！")
        return
      }
      const ids = this.selectDetailList.join(',')
      this.$modal.confirm('是否确认删除这"' + this.selectDetailList.length + '"条数据？').then(function() {
        return deleteImgCollectDetailByIds({ids: ids})
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getDetailsList(item.id,item)
      })
    },
    getImg(row){
      if(row.coverurl.startsWith('http')){
        return row.coverurl
      }
      const Authorization =  "Bearer " + getToken();
      return this.$config.urlFormat(`/file/viewFile?fileName=${row.coverurl}&token=${Authorization}`)
    },
    getPreviewPath(id,item){
      if(id?.startsWith('http')){
        return id
      }
      return this.$config.urlFormat('/openApi/previewByBussId?bussid=' + id)
    },
    getDirectionOptionsName(val){
      return directionOptions.find(item => item.value === val)?.label
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getPageData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getPageData()
    },
    handleAdd(){
      this.mode = 'add'
      this.itemObj = {}
      this.$refs.itemFormRef.handleOpen()
    },
    handleUpdate(){
      this.itemObj = Object.assign({}, this.multipleSelection[0])
      // this.$set(this,'itemObj',this.multipleSelection[0])
      this.mode = 'edit'
      this.$refs.itemFormRef.handleOpen()
    },
    handleDelete(){
      const ids = this.multipleSelection.map(item => item.id)
      this.$modal.confirm('是否确认删除这"' +this.multipleSelection.length + '"条数据？').then(function() {
        return deleteByIds({ids: ids})
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getPageData()
      }).catch(() => {});
    },
    handleDetail(){
      this.$refs.itemDetailRef.open()
    },
    toggleStatus(row) {
      const submitObj = Object.assign({}, row);
      update(submitObj).then(res => {
        this.$modal.msgSuccess("状态切换成功");
        this.getPageData();
      }).catch(() => {
        this.$modal.msgError("状态切换失败");
        // 回滚状态
        row.status = row.status === '0' ? '1' : '0';
      });
    },
    getAllSelectData(){
      return this.multipleSelection
    },
    // handleSelectionChange(val) {
    //   this.multipleSelection = this.detailList.filter(item => item.selected)
    //   this.single = this.multipleSelection.length === 1;
    //   this.multiple = this.multipleSelection.length > 1;
    // },
    expandChange(row){
      this.currentRow = row;
      this.drawerVisible = true;
      this.getDetailsList(row.id,row);
      this.selectDetailList = [];
    },
    getDetailsList(collid,row){
      this.$set(row,'detailList', [])
      getImgCollectDetailList({ collid: collid }).then(res => {
        this.$set(row,'detailList',res.data)
        // row.detailList = res.data
      })
    },
    getPageData(){
      const searchParams = {
        ...this.queryParams,
        alltypeid: this.activeId
      }
      getImgCollectPage(searchParams).then(res => {
        res?.rows?.forEach(item => {
          item.detailList = [];
          this.$set(item, 'selected', false);
        });
        this.tableData = res.rows
        this.total = res.total
      })
    },
    clickType(){
      this.getPageData()
    },
    async initTypeList(){
      const dataList = await getList({ bustype: 'coll' }).then(res => res.data )
      dataList.forEach((item) => {
        item.label = item.name
        item.value = item.id
      })
      const treeList = listToTree(dataList,'id','parentid')
      treeList.unshift(this.allObj)
      this.typeList = treeList
    },
    toggleRowSelection(row) {
      row.selected = !row.selected;
      const newSelection = this.multipleSelection.filter(item => item.id !== row.id);
      if (row.selected) {
        newSelection.push(row);
      }
      // this.handleSelectionChange(newSelection);
    }
  },
  async mounted() {
    await this.initTypeList()
    this.getPageData()
  }
}
</script>

<style scoped lang="scss">
.image-preview{
  width: 200px;
}
::v-deep{
  .el-divider{
    margin: 0 !important;
  }
  .el-table::before{
    display: none;
  }
}
</style>
